<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="订单号搜索"
        v-model="search.trade_no"></el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户名称搜索"
        v-model="search.remark"></el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="联系号码搜索"
        v-model="search.mobile"></el-input>
      <el-date-picker v-model="search_time" type="daterange" align="left" unlink-panels range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" class="filter-item"
        value-format="yyyy-MM-dd"></el-date-picker>
      <el-select @change='handleFilter' style="width: 140px" class="filter-item" v-model="search.status">
        <el-option label="全部" value=''></el-option>
        <el-option label="待接单" value='2'></el-option>
        <el-option label="配送中" value='3'></el-option>
        <el-option label="交易完成" value='4'></el-option>
        <el-option label="交易失败" value='5'></el-option>
        <el-option label="有退款" value='6'></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" plain v-waves icon="el-icon-search" @click="handleFilter">搜索
      </el-button>
    </div>
    <!-- // 这是列表 -->
    <el-table :data="listData" style="width: 100%" highlight-current-row default-expand-all max-width="250"
      :row-class-name="tableRowClassName" v-loading="listLoading" element-loading-text="给我一点时间">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.product" border highlight-current-row style="width: 100%"
            :row-class-name="tableOfGoods">
            <el-table-column type="index" width="50">#</el-table-column>
            <el-table-column label="状态" width="80">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 1">正常交易</span>
                <span v-else>已被退货</span>
              </template>
            </el-table-column>

            <el-table-column prop="product_name" label="商品名称" width="200"></el-table-column>
            <el-table-column prop="category_name" label="商品类型" width="200"></el-table-column>
            <el-table-column prop="price" label="价格" width="200"></el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">
                <span v-if="scope.row.amount > 1" style="color:red;font-size:16px">{{ scope.row.amount }}</span>
                <span v-else>{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <!-- // tab -->
      <el-table-column label="订单号" width="180px">
        <template slot-scope="scope">
          <el-tag type="success">{{scope.row.trade_no}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="联系号码" width="120px" prop="mobile">
        <template slot-scope="scope">
          <span style="color:red;font-size:16px">{{scope.row.mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column label="送货地址" width="180px" prop="address"></el-table-column>
      <el-table-column label="订单金额" width="100px">
        <template slot-scope="scope">
          <span style="font-size:16px">{{scope.row.total_fee}}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际到账" width="100px">
        <template slot-scope="scope">
          <span style="color:red;font-size:16px">{{scope.row.actual_fee}}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易方式" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.cash_type | statusFilter">{{scope.row.cash_type | statusName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配送员" width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.admin_mobile }} --</span>
          <span>{{ scope.row.admin_realname }} </span>
        </template>
      </el-table-column>
      <el-table-column label="创单时间" prop="created_at" width="160px"></el-table-column>
      <el-table-column label="交易状态" prop="status_name"></el-table-column>
      <el-table-column label="备注" prop="remark"></el-table-column>
      <el-table-column label="操作" width="250" class-name="small-padding fixed-width" align='center' fixed="right">
        <template slot-scope="scope">
          <el-button type="warning"
            v-if="(scope.row.cash_type==2 && scope.row.status==1) || (scope.row.status==2 && scope.row.cash_type==1)"
            icon="el-icon-bell" size="mini" @click="handleAdopt(scope.row, 3)">接单</el-button>
          <el-button type="success" v-if="scope.row.status==3" icon="el-icon-star-on" size="mini"
            @click="handleAdopt(scope.row, 4)">送达</el-button>
          <el-button type="danger" v-if="scope.row.status==3" icon="el-icon-warning" size="mini"
            @click="handleAdopt(scope.row, 5)">未完成</el-button>
          <el-button type="primary" v-if="(scope.row.status<4)" icon="el-icon-edit" size="mini"
            @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" v-if="scope.row.status==1" icon="el-icon-close" size="mini"
            @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>


    <!-- 弹框编辑 -->
    <el-dialog title="编辑部分信息" :visible.sync="editVisible">
      <el-form :rules="rules" ref="tempForm" :model="editTemp" label-position="left" label-width="80px"
        style='width: 400px; margin-left:60px;' class="demo-ruleForm">
        <el-form-item label="订单号">
          <el-input class="filter-item" v-model="editTemp.trade_no" readonly="readonly"></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input class="filter-item" placeholder="输入收货地址" v-model="editTemp.address"></el-input>
        </el-form-item>
        <el-form-item label="联系号码" prop="mobile">
          <el-input class="filter-item" placeholder="输入收货地址" v-model="editTemp.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="handleEdit" v-roles="'editOrder'">确认修改</el-button>
      </span>
    </el-dialog>
    <!-- 弹框编辑 end-->

    <!--可自定义按钮的样式、show/hide临界点、返回的位置  -->
    <!--如需文字提示，可在外部添加element的<el-tooltip></el-tooltip>元素  -->
    <el-tooltip placement="top" content="回到顶部">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50">
      </back-to-top>
    </el-tooltip>

  </div>
</template>


<script>
  import waves from '@/directive/waves' // 水波纹指令
  import BackToTop from '@/components/BackToTop' // 回到顶部
  import * as api from '@/api/main-api' // API
  import {
    mapGetters
  } from 'vuex'

  export default {
    name: 'OrderList',
    directives: {
      waves
    },
    components: {
      BackToTop
    },
    data() {
      return {
        // 回到顶部样式
        myBackToTopStyle: {
          right: '50px',
          bottom: '50px',
          width: '40px',
          height: '40px',
          'z-index': '9999',
          'border-radius': '4px',
          'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
          background: '#e7eaf1' // 按钮的背景颜色 The background color of the button
        },
        // 长带参数
        listQuery: {
          page: 1,
          pagesize: 10
        },
        // 搜索字段
        search: {
          trade_no: '',
          status: ''
        },
        search_time: '',

        total: 0,
        listLoading: false,
        editLoading: false,
        editVisible: false,
        listData: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        // 编辑
        editTemp: {
          address: '',
          mobile: '',
          trade_no: '',
          id: 0
        },
        rules: {
          address: [{
            required: true,
            message: '请输收货地址',
            trigger: 'blur'
          }],
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              pattern: /^1[3456789]\d{9}$/,
              message: '目前只支持中国大陆的手机号码'
            },
            {
              validator: function (rule, value, callback) {
                var MobileRegex = /^1[0-9]{10}$/
                if (!MobileRegex.test(value)) {
                  callback(new Error('手机号码格式不正确！'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          id: [{
            required: true,
            message: 'id 不能为空',
            trigger: 'blur'
          }]
        }
      }
    },

    // 初始化数据
    created() {
      this.listQuery.unit_id = this.outlet_id
      setTimeout(() => {
        this.fetchData()
      }, 100)
    },

    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'info',
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      },

      statusName(status) {
        return (status === '1') ? '线上付款' : '货到付款'
      }
    },

    computed: {
      ...mapGetters([
        'outlet_id'
      ])
    },

    // 触动方法
    methods: {

      // 控制每页调数
      handleSizeChange(val) {
        this.listQuery.pagesize = val
        this.fetchData()
      },

      // 跳页
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.fetchData()
      },

      // 搜搜
      handleFilter() {
        this.listQuery.page = 1
        // 复制一个对象<br>var obj = { a: 1 ,b:2};
        if (this.search_time) {
          this.search.stime = this.search_time[0]
          this.search.etime = this.search_time[1]
        }
        this.listQuery = Object.assign(this.listQuery, this.search)
        this.fetchData()
      },

      // 编辑弹框
      handleUpdate(row) {
        this.editVisible = true
        this.editTemp.address = row.address
        this.editTemp.mobile = row.mobile
        this.editTemp.trade_no = row.trade_no
        this.editTemp.id = row.id
      },

      // 编辑提交
      handleEdit() {
        var params = {
          address: this.editTemp.address,
          id: this.editTemp.id,
          mobile: this.editTemp.mobile
        }
        api.editOrderApi(params).then(response => {
          if (response.data.code === 0) {
            this.$root.message('修改成功', 'success')
            this.fetchData()
          }
        })
        this.editVisible = false
      },

      // 获取数据
      fetchData() {
        this.listLoading = true
        return new Promise((resolve, reject) => {
          api.orderApi(this.listQuery).then(response => {
            if (response.data.code === 0) {
              this.listData = response.data.data
              this.total = parseInt(response.data.total)
            }
            this.listLoading = false
          })
        })
      },

      // 主订单行颜色
      tableRowClassName({
        row,
        rowIndex
      }) {
        return 'success-row'
      },

      // 商品table行颜色
      tableOfGoods({
        row,
        rowIndex
      }) {
        if (row.status === '2') {
          return 'warning-row'
        }
      },

      // 订单删除
      handleDel(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var params = {
            id: row.id,
            unit_id: this.outlet_id
          }
          api.delOrderApi(params).then(response => {
            if (response.data.code === 0) {
              const index = this.listData.indexOf(row)
              this.listData.splice(index, 1)
              this.$root.message('已移除订单', 'success')
              this.total = this.total - 1
            }
          })
        }).catch(() => {
          this.$root.message('已取消删除', 'info')
        })
      },

      // 接单操作,返回接单用户
      handleAdopt(row, status) {
        var params = {
          status: status,
          id: row.id
        }
        api.disposeApi(params).then(response => {
          if (response.data.code === 0) {
            this.$root.message('操作成功', 'success')
            if (status === 3) {
              row.status_name = '已被接单'
            } else if (status === 4) {
              row.status_name = '交易完成'
            } else {
              row.status_name = '交易失败'
            }
            row.status = status
            row.actual_fee = response.data.data.actual_fee // 实际到账
            row.admin_mobile = response.data.data.mobile
            row.admin_realname = response.data.data.realname
          }
        })
      }

    },

    // 监事事件
    watch: {
      outlet_id(id) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.listQuery.unit_id = id
            this.fetchData()
          }, 20)
        })
      }
    }
  }

</script>


<style>
  .el-table .success-row {
    background: #e5f1f5;
  }

  .el-table .warning-row {
    background: rgb(230, 148, 148);
  }

</style>
